package com.itheima.countroller;

import com.itheima.cammon.CommonResult;
import com.itheima.cammon.PageInof;
import com.itheima.pojo.Employee;
import com.itheima.service.EmployeeService;
import com.itheima.vo.EmployeeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 王同学
 */
@RequestMapping("/employee")
@RestController
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")
    public CommonResult login(@RequestBody Employee employee) {
        EmployeeVO employeeVO = employeeService.login(employee.getUsername(), employee.getPassword());

        if (employeeVO == null) {
            CommonResult.error("用户名或者密码错误");
        }
        //把vo的东西返上去给前端看
        return CommonResult.success(employeeVO);
    }

    /* @GetMapping
     public CommonResult getEmployee(){
         return CommonResult.success("访问成功~！");
     }*/
    @PostMapping("/logout")
    public CommonResult logout(HttpServletRequest request) {
        String token = request.getHeader("Authorization");//这个参数是接口文档那边写的
        employeeService.clearToken(token);
        return CommonResult.success("成功退出下线~！");
    }

    //这边写新增员工
    @PostMapping
    public CommonResult add(@RequestBody Employee employee) {
        //这边去调用服务层的判断方法，做各种判断
        return CommonResult.success(employeeService.add(employee));
    }

    //这边写通过id查询
    @GetMapping("/{id}")
    public CommonResult getById(@PathVariable("id") String id) {
        //这边去查询 看数据库中有没有这个员工id

        return CommonResult.success(employeeService.getById(id));
    }

    //这边写分页查询
    @GetMapping("/page")             //Request Param请求参数也就是设置默认值，当没有参数传进来的时候提供的一个默认值
    public CommonResult page(String name,
                             @RequestParam(defaultValue = "1") Integer start,
                             @RequestParam(defaultValue = "10") Integer pageSize) {
        //分页查询
        PageInof<Employee> res = employeeService.page(name, start, pageSize);
        return CommonResult.success(res);
    }

    //修改/启用/禁用
    @PutMapping
    public CommonResult update(@RequestBody Employee employee) {
        employeeService.update(employee);

        return CommonResult.success("修改成功~！");
    }
}
